//
//  LGMemberManageController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/2/27.
//

#import "LGMemberManageController.h"
//患者详情 - 癌症（圆荷健康）
#import "LGPatientDetailController_YHJK.h"
#import "LGPatientDetailController2.h"
#import "LGMemberManageCell.h"
#import "LGPatientModel.h"
@interface LGMemberManageController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
/**   */
@property (nonatomic , strong)UIView *searchIcon;
/**   */
@property (nonatomic , strong)UITextField *searchTF;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *finishBtn;
/**   */
@property (nonatomic , strong)UIButton *deleteBtn;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSMutableArray *selectArray;
/**   */
@property (nonatomic , copy)NSString *keyword;
@end

@implementation LGMemberManageController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.keyword = @"";
    [self.view addSubview:self.searchTF];
    [self.view addSubview:self.tableView];
    if(self.isAdd == YES){
        self.title = @"添加患者";
        [self.view addSubview:self.finishBtn];
        self.tableView.frame = CGRectMake(0, viewPix(77), Screen_W, Screen_H-topBarHeight-viewPix(77)-viewPix(70)-bottomSafeBarHeight/2.0);
    }else{
        self.title = @"移除患者";
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.deleteBtn];
        self.tableView.frame = CGRectMake(0, viewPix(77), Screen_W, Screen_H-topBarHeight-viewPix(77));
    }
    [self emptyViewWithSuperView:self.view frame:CGRectMake(0, viewPix(77), Screen_W, Screen_H-topBarHeight-viewPix(77))];
    [self requestData];
}

-(void)setIsAdd:(BOOL)isAdd{
    _isAdd = isAdd;
}
                            

-(void)requestData{
    NSString *action = (self.isAdd == YES)?@"/doctor/patient.group/patientNotInGroup":@"/doctor/patient.group/patientList";
    [RequestUtil withPOST:action parameters:@{@"group_id":self.groupid,@"keyword":self.keyword} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if (code == 200) {
            self.dataArray = [LGPatientModel mj_objectArrayWithKeyValuesArray:returnData];
        }
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无数据" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:LGErrorMessage offset:0];
        }
    }];
}

//添加成员
-(void)finishBtnAction{
    NSString *patientids = LGNSString(self.selectArray[0]);
    for (NSInteger i=1; i<self.selectArray.count; i++) {
        patientids = [NSString stringWithFormat:@"%@,%@",patientids,self.selectArray[i]];
    }
    [RequestUtil withPOST:@"/doctor/patient.group/patientAdd" parameters:@{@"group_id":self.groupid,@"patient_ids":patientids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [TooltipView showMessage:@"添加成功" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:LGErrorMessage offset:0];
    }];
}

//移除成员
-(void)deleteBtnAction{
    if(self.selectArray.count == 0){
        [TooltipView showMessage:@"请先选择要删除的患者" offset:0];
        return;
    }
    NSString *patientids = LGNSString(self.selectArray[0]);
    for (NSInteger i=1; i<self.selectArray.count; i++) {
        patientids = [NSString stringWithFormat:@"%@,%@",patientids,self.selectArray[i]];
    }
    [RequestUtil withPOST:@"/doctor/patient.group/patientRemove" parameters:@{@"group_id":self.groupid,@"patient_ids":patientids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [TooltipView showMessage:@"移除成功" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:LGErrorMessage offset:0];
    }];
}

-(void)selectBtnAction:(UIButton *)sender{
    NSInteger index = sender.tag-1000;
    LGPatientModel *model = self.dataArray[index];
    if(sender.selected == YES){
        [self.selectArray removeObject:model.patient_id];
    }else{
        [self.selectArray addObject:model.patient_id];
    }
    sender.selected = !sender.selected;
    NSInteger count = self.selectArray.count;
    if(self.isAdd == YES){
        NSString *title = (count>0)?[NSString stringWithFormat:@"完成（%ld）",count]:@"完成";
        self.finishBtn.selected = (count>0)?NO:YES;
        self.finishBtn.userInteractionEnabled = (count>0)?YES:NO;
        [self.finishBtn setTitle:title forState:UIControlStateNormal];
    }else{
        NSString *title = (count>0)?[NSString stringWithFormat:@"移除（%ld）",count]:@"移除";
        [self.deleteBtn setTitle:title forState:UIControlStateNormal];
    }
}

-(void)textFieldValueChanged:(UITextField *)textField{
    self.keyword = textField.text;
    [self requestData];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if(textField.returnKeyType == UIReturnKeyDone){
        [self.searchTF endEditing:YES];
    }
    return YES;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGMemberManageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.lineView.hidden = (indexPath.row == self.dataArray.count-1)?YES:NO;
    cell.selectBtn.tag = 1000+indexPath.row;
    LGPatientModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    cell.selectBtn.selected = [self.selectArray containsObject:model.patient_id]?YES:NO;
    [cell.selectBtn addTarget:self action:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LGPatientModel *model = self.dataArray[indexPath.row];
    //癌症-患者详情
    if ([model.nodepage isEqualToString:@"1"]) {
        LGPatientDetailController2 *controller = [[LGPatientDetailController2 alloc]init];
        controller.patientid = LGNSString(model.patient_id);
        controller.diseaseCode = LGNSString(model.disease_code);
        controller.levelid = LGNSString(model.level_id);
        [self.navigationController pushViewController:controller animated:YES];
        
    }else{
        LGPatientDetailController_YHJK *controller = [[LGPatientDetailController_YHJK alloc]init];
        controller.patientid = LGNSString(model.patient_id);
        controller.diseaseCode = LGNSString(model.disease_code);
        controller.levelid = LGNSString(model.level_id);
        [self.navigationController pushViewController:controller animated:YES];
    }
}

-(NSMutableArray *)selectArray{
    if(!_selectArray){
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

-(UIView *)searchIcon{
    if(!_searchIcon){
        _searchIcon = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewPix(36), viewPix(54))];
        UIButton *button = [UIButton buttonWithImage:@"searchGray16" selectImage:@"searchGray16"];
        button.frame = CGRectMake(0, 0, viewPix(36), viewPix(54));
        [_searchIcon addSubview:button];
    }
    return _searchIcon;
}

-(UITextField *)searchTF{
    if(!_searchTF){
        _searchTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(16), Screen_W-viewPix(32), viewPix(54))];
        [_searchTF setShadoWithColor:@"#B3C5D9" offset:CGSizeMake(0, 0) opacity:0.15 radius:15];
        _searchTF.tintColor = [UIColor colorWithString:@"#333333"];
        _searchTF.textColor = [UIColor colorWithString:@"#333333"];
        _searchTF.backgroundColor = [UIColor whiteColor];
        _searchTF.textAlignment = NSTextAlignmentLeft;
        _searchTF.returnKeyType = UIReturnKeyDone;
        _searchTF.placeholder = @"搜索";
        _searchTF.font = LGFont(16);
        _searchTF.delegate = self;
        _searchTF.leftViewMode = UITextFieldViewModeAlways;
        _searchTF.leftView = self.searchIcon;
        [_searchTF addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTF;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, viewPix(77), Screen_W, Screen_H-topBarHeight-viewPix(77)) style:UITableViewStylePlain];
        [_tableView registerClass:[LGMemberManageCell class] forCellReuseIdentifier:@"cell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = viewPix(65);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(25))];
        _tableView.tableFooterView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(25))];
    }
    return _tableView;
}


-(UIButton *)finishBtn{
    if(!_finishBtn){
        _finishBtn = [UIButton buttonWithTitle:@"完成" topMargin:Screen_H-topBarHeight-viewPix(70)-bottomSafeBarHeight/2.0];
        _finishBtn.selected = YES;
        _finishBtn.userInteractionEnabled = NO;
        [_finishBtn addTarget:self action:@selector(finishBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _finishBtn;
}

-(UIButton *)deleteBtn{
    if(!_deleteBtn){
        _deleteBtn = [UIButton buttonWithTitle:@"移除" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#EB5757" imageName:@""];
        _deleteBtn.frame = CGRectMake(0, 0, viewPix(75), 44);
        _deleteBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_deleteBtn addTarget:self action:@selector(deleteBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
